package club.gskj.gulimall.order.controller;

import club.gskj.gulimall.order.entity.OrderEntity;
import club.gskj.gulimall.order.entity.OrderReturnReasonEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Correlation;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.UUID;

@Slf4j
@RestController
public class RabbitController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /***
     * 模拟发送多条不同类型的Message消息
     */
    @GetMapping("/sendMessage")
    public String sendMessage() {
        // 模拟发送多条messgae
        for (int i = 0; i < 10; i++) {

            if (i % 2 == 0) {
                // 如果携带的消息为对象类型，会默认使用JDK序列化机制，将对象写出去，该对象必须实现 Serializable接口
                OrderReturnReasonEntity order = new OrderReturnReasonEntity();
                order.setCreateTime(new Date());
                order.setId(1L);
                order.setName("test-connor- " + i);
                order.setSort(1);
                order.setStatus(1);
                // 设置发送的对象消息为 JSON格式。
                // 默认使用 org.springframework.amqp.support.converter.MessageConverter的实现类：SimpleMessageConverter，需用JDK序列化机制
                // 使用自定义 MessageConverter 来设置消息格式为Json。

                // 发送消息到 交换器
                // CorrelationData 指定每个消息的唯一id
                rabbitTemplate.convertAndSend("hello.java.exchange", "hello.java", order, new CorrelationData(UUID.randomUUID().toString()));
            } else {
                OrderEntity orderEntity = new OrderEntity();
                orderEntity.setOrderSn(i + "");
                rabbitTemplate.convertAndSend("hello.java.exchange", "hello1.java", orderEntity, new CorrelationData(UUID.randomUUID().toString()));
            }
        }
        log.info("消息发送成功");
        return "success";
    }
}
